<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert show-icon type="warning" :closable="false">注意：只允许为第三级分类设置相关参数!</el-alert>
            <el-row class="cat_opt">
                <el-col>
                    选择商品分类：
                    <el-cascader
                            v-model="selectedKeys"
                            :options="cateList"
                            :props="cateProps"
                            @change="handleCatChange"
                            >
                    </el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="!selectedKeys.length" @click="showAddDialog('addFormRef')">
                    添加参数
                </el-button>
                    <el-table
                    :data="manyTableData"
                    border
                    stripe
                    :header-cell-style="{textAlign: 'center'}"
                    :cell-style="{ textAlign: 'center' }"
                    >
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag
                                        :key="index"
                                        v-for="(tag,index) in getDynamicTags(scope.row)"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(scope.row,index)">
                                    {{tag}}
                                </el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="$event.target.blur"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#" type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-danger" @click="deleteParam(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" :disabled="!selectedKeys.length" @click="showAddDialog">
                        添加属性
                    </el-button>
                    <el-table
                            :data="onlyTableData"
                            border
                            stripe
                            :header-cell-style="{textAlign: 'center'}"
                            :cell-style="{ textAlign: 'center' }"
                    >
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag
                                        :key="index"
                                        v-for="(tag,index) in getDynamicTags(scope.row)"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleClose(scope.row,index)">
                                    {{tag}}
                                </el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="$event.target.blur"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#" type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-danger" @click="deleteParam(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <el-dialog
                :title="'添加'+titleText"
                :visible.sync="addDialogVisible"
                width="50%"
                >
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item prop="attr_name" label="参数名称">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="add('addFormRef')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
                :title="'修改'+titleText"
                :visible.sync="editDialogVisible"
                width="50%"
        >
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item prop="attr_name" label="参数名称">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="edit('editFormRef')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
  export default {
    name: "Params",
    data() {
      return {
        cateList: [],
        cateProps: {
          expandTrigger: 'hover',
          value:'cat_id',
          label:'cat_name',
        },
        selectedKeys:[],
        activeName:'many',
        manyTableData:[],
        onlyTableData:[],
        addForm:{
          attr_name:'',
          attr_sel:this.activeName,
          attr_vals:'test'
        },
        addFormRules:{
          attr_name:[
            {required:true,message:'请输入参数名称',trigger:'blur'}
          ]
        },
        addDialogVisible:false,
        editDialogVisible:false,
        editForm:{},
        editFormRules:{
          attr_name:[
            {required:true,message:'请输入参数名称',trigger:'blur'}
          ]
        },
        dynamicTags:[],
      }
    },
    created() {
      this.getCateList();
    },
    methods: {
      async getParamsData(){
        if (this.selectedKeys.length !== 3){
          this.selectedKeys = [];
          this.manyTableData = [];
          this.onlyTableData = [];
          return ;
        }
        const {data:res} = await this.$http({
          url:`categories/${this.selectedKeys[this.selectedKeys.length-1]}/attributes`,
          method:'get',
          params:{sel:this.activeName}
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取参数失败');
        res.data.forEach(value => {
          value.inputVisible = false;
          value.inputValue = '';
        });
        if (this.activeName === 'many'){
          this.manyTableData = res.data;
        }else {
          this.onlyTableData = res.data;
        }
      },
      async getCateList() {
        const {data: res} = await this.$http({
          url: 'categories',
          method: 'get',
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取分类列表失败');
        this.cateList = res.data;
      },
      async handleCatChange(){

        this.getParamsData();
      },
      handleClick(){
        this.getParamsData();
      },
      showAddDialog(formName){
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields();
        }
        this.addDialogVisible = true;
      },
      add(formName){
        this.addForm.attr_sel = this.activeName;
        this.$refs[formName].validate(async (valid) => {
          if (!valid) return this.$message.error('表单不合法');
          const {data:res} = await this.$http({
            url:`categories/${this.selectedKeys[this.selectedKeys.length-1]}/attributes`,
            method:'post',
            data:this.addForm
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 201) return this.$message.error('添加参数失败');
          this.$message.success('添加参数成功');
          this.getParamsData();
          this.addDialogVisible = false;

        });
      },
      async deleteParam(attr_id){
        const {data:res} = await this.$http({
          url:`categories/${this.selectedKeys[this.selectedKeys.length-1]}/attributes/${attr_id}`,
          method:'delete'
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('删除失败');
        this.getParamsData();
        this.$message.success('删除成功');
      },
      async showEditDialog(attr_id){
        const {data:res} = await this.$http({
          url:`categories/${this.selectedKeys[this.selectedKeys.length-1]}/attributes/${attr_id}`,
          method:'get'
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取参数失败');
        this.editForm = res.data;
        this.editDialogVisible = true;
      },
      edit(formName){
        this.$refs[formName].validate(async (valid) => {
          if (!valid) return this.$message.error('表单不合法');
          const {data:res} = await this.$http({
            url:`categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
            method:'put',
            data:this.editForm
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error('修改参数失败');
          this.getParamsData();
          this.editDialogVisible = false;
          this.$message.success('更新成功');
        });
      },
      async handleInputConfirm(row){
        if (row.inputValue.trim() === '') return this.$message.error('不能为空');
        row.attr_vals  = `${row.attr_vals},${row.inputValue}`;
        row.inputVisible = false;
        this.editForm.attr_vals = row.attr_vals;
        const {data:res2} = await this.$http({
          url:`categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
          method:'put'
        });
        if (res2.meta.status === 403) return this.$message.error(res2.meta.msg);
        if (res2.meta.status !== 200) return this.$message.error('修改参数失败');
        this.editDialogVisible = false;
        this.$message.success('更新成功');

      },
      async handleClose(row,index){
        let arr = row.attr_vals.split(',');
        arr.splice(index,1);
        row.attr_vals = arr.join(',');
        const {data:res1} = await this.$http({
          url:`categories/${this.selectedKeys[this.selectedKeys.length-1]}/attributes/${row.attr_id}`,
          method:'get'
        });
        if (res1.meta.status === 403) return this.$message.error(res1.meta.msg);
        if (res1.meta.status !== 200) return this.$message.error('获取参数失败');
        this.editForm = res1.data;
        this.editForm.attr_vals = row.attr_vals;
        const {data:res2} = await this.$http({
          url:`categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
          method:'put'
        });
        if (res2.meta.status === 403) return this.$message.error(res2.meta.msg);
        if (res2.meta.status !== 200) return this.$message.error('修改参数失败');
        this.editDialogVisible = false;
        this.$message.success('更新成功');
      },
      getDynamicTags(row){
        if (row.attr_vals.split(',')[0] === ""){
          return [];
        }
        return row.attr_vals.split(',');
      },
      async showInput(row){
        row.inputValue = '';
        row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
        const {data:res1} = await this.$http({
          url:`categories/${this.selectedKeys[this.selectedKeys.length-1]}/attributes/${row.attr_id}`,
          method:'get'
        });
        if (res1.meta.status === 403) return this.$message.error(res1.meta.msg);
        if (res1.meta.status !== 200) return this.$message.error('获取参数失败');
        this.editForm = res1.data;

      }
    },
    computed:{
      titleText(){
        if (this.activeName === 'many'){
          return '动态参数';
        }
        return '静态属性';
      },
    }
  }
</script>

<style scoped>
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: center;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .el-tag{
        margin: 10px;
    }
    .cat_opt {
        margin: 20px 0;
    }
    .el-breadcrumb{
        margin-bottom: 20px;
    }
    .el-table{
        margin-top: 20px;
    }
</style>